<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <span>我的订单</span>
      </template>

      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 180px">
            <el-option label="待支付" value="0" />
            <el-option label="已支付" value="1" />
            <el-option label="已取消" value="2" />
            <el-option label="已退票" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="出行日期" style="width: 308px">
          <el-date-picker
            v-model="daterangeTravelDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 订单列表 -->
      <el-table v-loading="loading" :data="orderList" style="width: 100%">
        <el-table-column label="订单编号" align="center" prop="trainOrderId" width="120" />
        
        <el-table-column label="车次信息" align="left" width="250">
          <template #default="scope">
            <div>
              <p><strong>{{ scope.row.trainNumber }}</strong> {{ scope.row.trainName }}</p>
              <p style="color: #666; font-size: 12px;">
                {{ scope.row.departureStation }} → {{ scope.row.arrivalStation }}
              </p>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="乘客信息" align="left" width="180">
          <template #default="scope">
            <div>
              <p>{{ scope.row.passengerName }}</p>
              <p style="color: #666; font-size: 12px;">{{ scope.row.passengerPhone }}</p>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="座位信息" align="center" width="150">
          <template #default="scope">
            <div>
              <p>{{ scope.row.seatClass === 'business' ? '商务座' : scope.row.seatClass === 'first' ? '一等座' : '二等座' }}</p>
              <p style="color: #666; font-size: 12px;">{{ scope.row.carriageNumber }}车{{ scope.row.seatNumber }}</p>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="出行日期" align="center" prop="travelDate" width="120" />

        <el-table-column label="订单金额" align="center" width="100">
          <template #default="scope">
            <span style="color: #e6a23c; font-weight: bold">￥{{ scope.row.orderAmount }}</span>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" width="180">
          <template #default="scope">
            <span>{{ formatTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button 
              v-if="scope.row.orderStatus === '0'" 
              type="primary" 
              size="small" 
              @click="handlePay(scope.row)"
            >
              支付
            </el-button>
            <el-button 
              v-if="scope.row.orderStatus === '0'" 
              type="danger" 
              size="small" 
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button 
              v-if="scope.row.orderStatus === '1'" 
              type="warning" 
              size="small" 
              @click="handleRefund(scope.row)"
            >
              退票
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup name="MyOrders">
import { ref, reactive, onMounted } from 'vue'
import { listTrainorder, updateTrainorder } from "@/api/boot/trainorder"

const { proxy } = getCurrentInstance()

const orderList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const daterangeTravelDate = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderStatus: null
})

// 获取当前用户的订单列表
function getList() {
  loading.value = true
  queryParams.params = {}
  
  // 添加出行日期范围查询
  if (daterangeTravelDate.value && daterangeTravelDate.value.length === 2) {
    queryParams.params["beginTravelDate"] = daterangeTravelDate.value[0]
    queryParams.params["endTravelDate"] = daterangeTravelDate.value[1]
  }
  
  // 只查询当前用户的订单
  queryParams.userId = proxy.$store.state.user.userId
  
  listTrainorder(queryParams).then(response => {
    orderList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索按钮操作
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  daterangeTravelDate.value = []
  queryParams.orderStatus = null
  handleQuery()
}

// 支付订单
function handlePay(row) {
  proxy.$modal.confirm('确认要支付此订单吗？').then(() => {
    const updateData = {
      trainOrderId: row.trainOrderId,
      orderStatus: '1' // 已支付
    }
    
    updateTrainorder(updateData).then(response => {
      proxy.$modal.msgSuccess("支付成功")
      getList()
    })
  }).catch(() => {})
}

// 取消订单
function handleCancel(row) {
  proxy.$modal.confirm('确认要取消此订单吗？').then(() => {
    const updateData = {
      trainOrderId: row.trainOrderId,
      orderStatus: '2' // 已取消
    }
    
    updateTrainorder(updateData).then(response => {
      proxy.$modal.msgSuccess("订单已取消")
      getList()
    })
  }).catch(() => {})
}

// 退票操作
function handleRefund(row) {
  proxy.$modal.confirm('确认要退票吗？退票后将退回原支付方式').then(() => {
    const updateData = {
      trainOrderId: row.trainOrderId,
      orderStatus: '3' // 已退票
    }
    
    updateTrainorder(updateData).then(response => {
      proxy.$modal.msgSuccess("退票成功")
      getList()
    })
  }).catch(() => {})
}

// 获取状态标签类型
function getStatusType(status) {
  const statusMap = {
    '0': 'warning',  // 待支付
    '1': 'success',  // 已支付
    '2': 'danger',   // 已取消
    '3': 'info'      // 已退票
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    '0': '待支付',
    '1': '已支付',
    '2': '已取消',
    '3': '已退票'
  }
  return statusMap[status] || '未知'
}

// 格式化时间
function formatTime(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-table .cell {
  word-break: break-all;
}
</style>